package com.oscar.ehome.view.setview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.oscar.ehome.R;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.setbean.LearnHistoryBean;
import com.oscar.ehome.presenter.SetPresenter;
import com.oscar.ehome.utils.pullrefresh.PullToRefreshBase;
import com.oscar.ehome.utils.pullrefresh.PullToRefreshListView;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.view.MyList;
import com.oscar.ehome.utils.view.progressview.ProgressFrameLayout;
import com.oscar.ehome.utils.xrefresh.XRefreshView;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.messageview.MessageDetilActivity;
import com.oscar.ehome.view.pageview.ExcelDetialActivity;
import com.oscar.ehome.view.pageview.FrequencyActivity;
import com.oscar.ehome.view.pageview.PdfDetialActivity;
import com.oscar.ehome.view.pageview.StudyActivity;
import com.oscar.ehome.view.pageview.VideoActivity;
import com.oscar.ehome.view.pageview.adapter.StudyAdapter;
import com.oscar.ehome.view.setview.view.LearnHistoryView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by juxing
 * author: MengWanhe
 * date: On 2017/7/21
 * 学习历史记录
 */

public class LearnHistoryActivity extends BasesActivity<LearnHistoryView, SetPresenter> implements XRefreshView.XRefreshViewListener,
        AdapterView.OnItemClickListener, LearnHistoryView, ProgressFrameLayout.AgainRequestListener {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * 历史记录
     */
    @BindView(R.id.learn_listview)
    MyList learnListview;
    /**
     * 无网络布局
     */
    @BindView(R.id.learn_fragment)
    ProgressFrameLayout learnFragment;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    @BindView(R.id.message_refview)
    XRefreshView messageRefview;

    List<LearnHistoryBean.LearnListBean> list = new ArrayList<>();//加载数据
    List<LearnHistoryBean.LearnListBean> learnListgengduo = new ArrayList<>();//加载数据
    SetPresenter setPresenter;
    StudyAdapter adapter;
    public static long lastRefreshTime;
    String token = "";

    private int page = 1;//页数
    private int page_size = 20;//每页的条数
    int size = 0;
    int count = 0;//条数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_learnhistory);
        ButterKnife.bind(this);
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(LearnHistoryActivity.this).getSystemConfig().getColor()));
        initView();
        onClicks();
        initData();
    }

    @Override
    protected SetPresenter createPresenter() {
        setPresenter = new SetPresenter(this);
        return setPresenter;
    }

    /**
     * 判断是否有网
     */
    public boolean isNetWork() {
        boolean netWork = true;
        if (!CommonUtils.isNetConn(LearnHistoryActivity.this)) {
            netWork = false;
            return netWork;
        }
        return netWork;
    }

    /**
     * 初始化数据
     */
    public void initView() {
        titleImgBack.setImageResource(R.mipmap.fanhui);
        titleImgBack.setVisibility(View.VISIBLE);
        titleTopbar.setText("学习历史");
        token = SystemConfigFactory.getInstance(LearnHistoryActivity.this).getSystemConfig().getToken();
        setPresenter = new SetPresenter(this);
        adapter = new StudyAdapter(LearnHistoryActivity.this, list);
        learnListview.setAdapter(adapter);
    }

    public void onClicks() {

        messageRefview.setXRefreshViewListener(this);
        // 设置是否可以下拉刷新
        messageRefview.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        messageRefview.setPullLoadEnable(true);
        // 设置上次刷新的时间
        messageRefview.restoreLastRefreshTime(lastRefreshTime);
        //当下拉刷新被禁用时，调用这个方法并传入false可以不让头部被下拉
        messageRefview.setMoveHeadWhenDisablePullRefresh(true);
        // 设置时候可以自动刷新
        messageRefview.setAutoRefresh(false);
        learnListview.setOnItemClickListener(this);
        learnFragment.setAgainRequestListener(this);
    }

    /**
     * 请求数据
     */
    public void initData() {
        if (isNetWork()) {
            learnFragment.stopRefresh();
            learnListview.setVisibility(View.VISIBLE);
            setPresenter.getLearnList(token,"20",page+"");
            showLoading();
        } else {
            learnFragment.setVisibility(View.VISIBLE);
            learnListview.setVisibility(View.GONE);
            learnFragment.setLoadFail();
        }
    }

    @OnClick(R.id.title_layout_left)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String learnType = list.get(position).getLearn().getLearnType();
        if ("video/mp4".equals(learnType)) {//视频
            Intent intent = new Intent(LearnHistoryActivity.this, VideoActivity.class);
            intent.putExtra("id", list.get(position).getLearn().getId());
            startActivity(intent);
        } else if ("application/pdf".equals(learnType)) {//PDF
            Intent intent = new Intent(LearnHistoryActivity.this, PdfDetialActivity.class);
            intent.putExtra("id", list.get(position).getLearn().getId());
            startActivity(intent);
        } else if ("audio/mp3".equals(learnType)) {//音频
            Intent intent = new Intent(LearnHistoryActivity.this, FrequencyActivity.class);
            intent.putExtra("id", list.get(position).getLearn().getId());
            startActivity(intent);
        } else if ("application/vnd.ms-excel".equals(learnType) || "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(learnType)) {
            Intent intent = new Intent(LearnHistoryActivity.this, ExcelDetialActivity.class);
            intent.putExtra("id", list.get(position).getLearn().getId());
            intent.putExtra("open", "false");
            startActivity(intent);

        }
    }


    @Override
    public void getLearnList(LearnHistoryBean sginchuqinBean) {
        dismissLoading();
        messageRefview.stopRefresh();
        if (sginchuqinBean != null) {
            learnFragment.stopRefresh();
            learnListview.setVisibility(View.VISIBLE);
            if (page == 1) {
                list.clear(); // 将原有的内容清空
                list = sginchuqinBean.getList();
                size = list.size();
            } else {
                learnListgengduo = sginchuqinBean.getList();
                size = learnListgengduo.size();
                for (int i = 0; i < learnListgengduo.size(); i++) {
                    list.add(learnListgengduo.get(i));
                }
            }
            if (size > 0) {
                learnListview.setVisibility(View.VISIBLE);

                if (size >= 20) {
                    messageRefview.setPullLoadEnable(true);
                } else {
                    messageRefview.setPullLoadEnable(false);
                }
                adapter.setLists(list);
            } else {
                learnListview.setVisibility(View.GONE);
                learnFragment.setVisibility(View.VISIBLE);
                learnFragment.setNoResult();
            }
        } else {
            learnListview.setVisibility(View.GONE);
            learnFragment.setNoResult();
        }

    }

    @Override
    public void erroy() {
        dismissLoading();
        messageRefview.stopRefresh();
        ToastUtil.show(LearnHistoryActivity.this, getString(R.string.erry));
    }

    @Override
    public void erry(String result) {
        dismissLoading();
        messageRefview.stopRefresh();
        Toast.makeText(LearnHistoryActivity.this, result, Toast.LENGTH_SHORT).show();
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(LearnHistoryActivity.this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(LearnHistoryActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void againRequest() {
        if (isNetWork()) {
            initData();
        } else {
            ToastUtil.show(LearnHistoryActivity.this, R.string.pull_to_refresh_network_error);
        }
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onRefresh(boolean isPullDown) {
        lastRefreshTime = messageRefview.getLastRefreshTime();
        messageRefview.restoreLastRefreshTime(lastRefreshTime);
        page = 1;
        initData();
    }

    @Override
    public void onLoadMore(boolean isSilence) {

        page++;
        initData();
        showLoading();
    }

    @Override
    public void onRelease(float direction) {

    }

    @Override
    public void onHeaderMove(double headerMovePercent, int offsetY) {

    }
}
